package com.huaxin.hxmoduleworkorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaxin.feignclient.system.SystemClient;
import com.huaxin.feignclient.system.models.SysUser;
import com.huaxin.hxmoduleworkorder.common.UserContext;
import com.huaxin.hxmoduleworkorder.dto.ResponseCode;
import com.huaxin.hxmoduleworkorder.dto.ResponseResult;
import com.huaxin.hxmoduleworkorder.dto.request.CustomerEvaluationCreateReqDTO;
import com.huaxin.hxmoduleworkorder.dto.request.CustomerEvaluationUpdateReqDTO;
import com.huaxin.hxmoduleworkorder.dto.request.GetCustomerEvaluationPageReqDTO;
import com.huaxin.hxmoduleworkorder.mapper.CustomerEvaluationMapper;
import com.huaxin.hxmoduleworkorder.mapping.CustomerEvaluationMapping;
import com.huaxin.hxmoduleworkorder.models.CustomerEvaluation;
import com.huaxin.hxmoduleworkorder.service.CustomerEvaluationService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 客户评价服务实现类（使用 MapStruct 映射）
 *
 * @author fuai
 * @since 2025-09-02
 */
@Service
@RequiredArgsConstructor
public class CustomerEvaluationServiceImpl extends ServiceImpl<CustomerEvaluationMapper, CustomerEvaluation>
        implements CustomerEvaluationService {

    private final CustomerEvaluationMapping customerEvaluationMapping;

    private final ApplicationContext applicationContext;

    private final SystemClient systemClient;

    @Override
    public ResponseResult<String> addCustomerEvaluation(CustomerEvaluationCreateReqDTO dto) {
        if (dto == null) {
            return ResponseResult.parameterError(null, "请求参数不能为空");
        }
        if (StringUtils.isBlank(dto.getMaintenanceOrderId())) {
            return ResponseResult.parameterError(null, "工单ID不能为空");
        }
        if (StringUtils.isBlank(dto.getCustomerId())) {
            return ResponseResult.parameterError(null, "客户ID不能为空");
        }
        if (dto.getRating() == null) {
            return ResponseResult.parameterError(null, "评分不能为空");
        }
        if (dto.getRating() < 1 || dto.getRating() > 5) {
            return ResponseResult.parameterError(null, "评分必须为1-5星");
        }
        if (dto.getElectricianIds() == null || dto.getElectricianIds().isEmpty()) {
            return ResponseResult.parameterError(null, "至少需要选择一位被评价的电工");
        }
        if (dto.getIsAnonymous() == null) {
            return ResponseResult.parameterError(null, "是否匿名字段不能为空");
        }

        if (this.hasEvaluated(dto.getMaintenanceOrderId(), dto.getCustomerId())) {
            return ResponseResult.failure(ResponseCode.BAD_REQUEST, "该工单已评价过，请勿重复评价", null);
        }

        CustomerEvaluation evaluation = customerEvaluationMapping.toEntity(dto);
        if (save(evaluation)) {
            return ResponseResult.ok("评价提交成功！");
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "评价提交失败，请稍后重试", null);
        }
    }

    @Override
    public ResponseResult<String> updateCustomerEvaluation(CustomerEvaluationUpdateReqDTO dto) {
        if (dto == null) {
            return ResponseResult.parameterError(null, "请求参数不能为空");
        }
        if (StringUtils.isBlank(dto.getId())) {
            return ResponseResult.parameterError(null, "评价ID不能为空");
        }
        CustomerEvaluation evaluation = getById(dto.getId());
        if (evaluation == null) {
            return ResponseResult.notFound(null, "评价记录不存在");
        }
        customerEvaluationMapping.updateEntity(dto, evaluation);
        if (updateById(evaluation)) {
            return ResponseResult.ok("评价更新成功！");
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "评价更新失败，请稍后重试", null);
        }
    }

    @Override
    public ResponseResult<String> deleteCustomerEvaluation(String id) {
        if (StringUtils.isBlank(id)) {
            return ResponseResult.parameterError(null, "评价ID不能为空");
        }

        CustomerEvaluation evaluation = getById(id);
        if (evaluation == null) {
            return ResponseResult.notFound(null, "评价记录不存在");
        }

        if (applicationContext.getBean(CustomerEvaluationService.class).removeById(id)) {
            return ResponseResult.ok("评价已删除！");
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "删除失败，请稍后重试", null);
        }
    }

    @Override
    public ResponseResult<CustomerEvaluation> getCustomerEvaluationById(String id) {
        if (StringUtils.isBlank(id)) {
            return ResponseResult.parameterError(null, "评价ID不能为空");
        }
        CustomerEvaluation evaluation = getById(id);
        if (evaluation != null) {
            return ResponseResult.ok(evaluation);
        } else {
            return ResponseResult.notFound(null, "评价记录不存在");
        }
    }

    @Override
    public ResponseResult<CustomerEvaluation> getEvaluationByOrderId(String maintenanceOrderId) {
        if (StringUtils.isBlank(maintenanceOrderId)) {
            return ResponseResult.parameterError(null, "工单ID不能为空");
        }
        LambdaQueryWrapper<CustomerEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerEvaluation::getMaintenanceOrderId, maintenanceOrderId);
        CustomerEvaluation evaluation = getOne(wrapper);
        if (evaluation != null) {
            return ResponseResult.ok(evaluation);
        } else {
            return ResponseResult.notFound(null, "该工单暂无评价");
        }
    }

    @Override
    public boolean hasEvaluated(String maintenanceOrderId, String customerId) {
        if (StringUtils.isAnyBlank(maintenanceOrderId, customerId)) {
            return false;
        }
        LambdaQueryWrapper<CustomerEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerEvaluation::getMaintenanceOrderId, maintenanceOrderId)
                .eq(CustomerEvaluation::getCustomerId, customerId);
        return count(wrapper) > 0;
    }

    //分页查询
    @Override
    public ResponseResult<Page<CustomerEvaluation>> getCustomerEvaluationPage(GetCustomerEvaluationPageReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "请求参数不能为空");
        }
        Page<CustomerEvaluation> page = new Page<>(in.getPageNum(), in.getPageSize());
        LambdaQueryWrapper<CustomerEvaluation> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(in.getOrderNumber())) {
            wrapper.like(CustomerEvaluation::getMaintenanceOrderId, in.getOrderNumber());
        }
        if (StringUtils.isNotBlank(in.getCustomerId())) {
            wrapper.eq(CustomerEvaluation::getCustomerId, in.getCustomerId());
        }
        if (StringUtils.isNotBlank(in.getCustomerName())) {
            wrapper.like(CustomerEvaluation::getCustomerName, in.getCustomerName());
        }
        if (StringUtils.isNotBlank(in.getPhone())) {
            wrapper.like(CustomerEvaluation::getCustomerPhone, in.getPhone());
        }
        return ResponseResult.ok(this.baseMapper.selectPage(page, wrapper));
    }

    @Override
    //回复客户评价
    public ResponseResult<String> replyCustomerEvaluation(String id, String replyContent) {
        if (StringUtils.isBlank(id)) {
            return ResponseResult.parameterError(null, "评价ID不能为空");
        }
        CustomerEvaluation evaluation = getById(id);
        if (evaluation == null) {
            return ResponseResult.notFound(null, "评价记录不存在");
        }
        evaluation.setReplyContent(replyContent);
        String userId = UserContext.getCurrentUserId();
        if (userId != null) {
            evaluation.setReplyUserId(userId);
            evaluation.setReplyTime(LocalDateTime.now());
            com.huaxin.feignclient.models.ResponseResult<SysUser> sysUser = systemClient.getSystemUserInfoById(userId);
            if (sysUser.getCode() == ResponseCode.SUCCESS.getCode() && sysUser.getData() != null) {
                evaluation.setReplyUserName(sysUser.getData().getRealName());
            }
        }
        if (updateById(evaluation)) {
            return ResponseResult.ok("评价回复成功！");
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_SERVER_ERROR, "评价回复失败，请稍后重试", null);
        }
    }
}